<template>
  <!-- 详情开始 -->
  <a-modal
    :maskClosable="false"
    title="合同详情"
    :width="1350"
    :bodyStyle="{
      padding: '0 24px'
    }"
    :visible="visible"
    @cancel="handleCancel"
    cancelText="关闭">
    <a-card
      :bordered="false"
      :bodyStyle="{
        padding: '10px 24px'
      }">
      <a-spin :spinning="confirmLoading">
        <j-form-container  id="contractmanageContent">
          <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
            <a-row :gutter="48">
              <a-col :span="8" :hidden="true">
                <a-form-model-item label="流程名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle"  >
                  <a-input :max-length="255" :disabled="formDisabled" v-model="model.bpmBizTitle" placeholder="请输入流程名称"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="finalNo">
                  <a-input  :disabled="formDisabled" v-model="model.htbh" placeholder="请输入单据编号"></a-input>
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                  <j-date  :disabled="formDisabled" placeholder="请选择申请时间" v-model="model.createTime" style="width: 100%"/>
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
                  <select-user-by-dep  :disabled="formDisabled" :multi="false" v-model="model.proposer"/>
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposerDeptId">
                  <j-select-depart  :disabled="formDisabled" v-model="model.proposerDeptId"/>
                </a-form-model-item>
              </a-col>
              <template v-if="model.htlx == '2'">
                <a-col :span="8">
                  <a-form-model-item label="申请人所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyTeam">
                    <select-team-input
                      :disabled="formDisabled"
                      placeholder="请选择申请人所属团队"
                      v-model="model.applyTeam"
                      :tdlx="1" />
                  </a-form-model-item>
                </a-col>
              </template>

              <a-divider>基本信息</a-divider>
              <template v-if="sfbg">
                <a-col :span="8">
                  <a-form-model-item label="合同编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="caId">
                    <select-contract-manager-input
                      :htlx="contractType"
                      :disabled="formDisabled"
                      v-model="model.caId"
                      :allList="true"
                      :status="'2'"
                      :muitFlag="true"
                      :changeStatus="'unchanged'"
                      @change="htbhChange"
                      :triggerChange="true"/>
                  </a-form-model-item>
                </a-col>
              </template>
              <a-col :span="8">
                <a-form-model-item label="合同名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="htmc">
                  <a-input  :disabled="formDisabled" v-model="model.htmc" placeholder="请输入合同名称"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="model.htlx == '2'">
                <a-form-model-item label="是否为采购类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isCategoryType">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="radio"
                    v-model="model.isCategoryType"
                    dictCode="is_category_type"
                    placeholder="请选择是否为采购类"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" :hidden="showByHtlx">
                <a-form-model-item label="合同类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="htlx" >
                  <j-dict-select-tag
                    :disabled="formDisabled ? true : sfbg"
                    type="list"
                    v-model="model.htlx"
                    dictCode="htlx_type"
                    placeholder="请选择合同类型"
                    @change="htlxChange"
                    :triggerChange="true"/>
                </a-form-model-item>
              </a-col>
              <template v-if="sfbg">
                <a-col :span="8">
                  <a-form-model-item label="变更类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bglx">
                    <j-dict-select-tag
                      :disabled="formDisabled"
                      type="list"
                      v-model="model.bglx"
                      dictCode="bglx_type"
                      placeholder="请选择变更类型"/>
                  </a-form-model-item>
                </a-col>
              </template>
              <a-col :span="8">
                <a-form-model-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="xmmc">
                  <a-input :readOnly="true" v-model="model.xmmc_dictText"  style="color: #1890FF;"   @click.prevent="getProjectDetail(model.xmmc)"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8"  v-show = "model.isCategoryType == '1'">
                <a-form-model-item label="采购类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="provisionType">
                  <j-dict-select-tag  type="list" dictCode="provision_type" :disabled="formDisabled"  v-model="model.provisionType" placeholder="请选择采购类型" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-show = "model.provisionType == '1'" >
                <a-form-model-item label="关联定标结果确认单" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="calibrationId">
                  <select-purchase-calibration-input :disabled="formDisabled" placeholder="请关联定标结果确认单" v-model="model.calibrationId" :projectId="model.xmmc"  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-show = "model.provisionType == '2'" >
                <a-form-model-item label="关联采购申请单" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseApplyId">
                  <select-purchase-apply-form-contract-input :disabled="formDisabled" placeholder="请关联采购申请单" v-model="model.purchaseApplyId" :projectId="model.xmmc"  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8" style="display:none">
                <a-form-model-item label="项目编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="xmbh">
                  <a-input  v-model="model.xmbh" placeholder="请输入项目编号"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="经营团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="jytd">
                  <select-team-input
                    :disabled="formDisabled"
                    v-model="model.jytd"
                    :tdlx="1"/>

                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="业绩归属年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="yjgsnd">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.yjgsnd"
                    dictCode="yjgsnd"
                    placeholder="请选择业绩归属年度"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="签订单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="qddw">
                  <select-Company-input :disabled="formDisabled" v-model="model.qddw" placeholder="请选择签订单位"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目承接人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="xmcjr">
                  <select-user-by-dep :disabled="formDisabled" :multi="false" v-model="model.xmcjr"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="业主单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="yzdw">
                  <!-- <select-customer-input
                    :disabled="formDisabled"
                    v-model="model.yzdw"
                    :commercialType="model.htlx"
                    @change="yzdwChange"/> -->
                    <!--迭代11 6.若合同类型为付款合同，业主单位改为取供应商改为待定-->
                    <select-customer-input
                    :disabled="formDisabled"
                    v-model="model.yzdw"
                    commercialType="1"
                    @change="yzdwChange"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="lxr">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.lxr"
                    :dictCode="cust_lxr"
                    placeholder="请选择联系人"
                    @change="lxrChange"
                    :triggerChange="true"/>

                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="联系方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="lxfs">
                  <a-input :disabled="formDisabled" v-model="model.lxfs" placeholder="请输入联系方式"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="签订日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="qdrq">
                  <j-date :disabled="formDisabled" placeholder="请选择签订日期" v-model="model.qdrq" style="width: 100%"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="履约保证金（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bail">
                  <a-input :disabled="formDisabled" placeholder="请选择签订日期" v-model="model.bail" :defaultValue="0" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="48">
              <a-col :span="8">
                <!--迭代11 1.是否用章改为是否用印，变更为必选项，不给默认值 -->
                <a-form-model-item label="是否用印" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sfyz">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="radio"
                    v-model="model.sfyz"
                    dictCode="yn"
                    @input="handleChangeSeal"
                    placeholder="请选择是否用印"/>
                </a-form-model-item>
              </a-col>
              <template v-if="model.sfyz == '0' && model.htlx == '1'">
                <a-col :span="8">
                  <a-form-model-item label="无正式合同" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="noFormalContract">
                    <j-dict-select-tag
                      :disabled="formDisabled"
                      type="radio"
                      v-model="model.noFormalContract"
                      dictCode="YES_OR_NO"
                      placeholder="请选择无正式合同"/>
                  </a-form-model-item>
                </a-col>
              </template>
              <a-col :span="8" v-if="isShowSeal">
                <a-form-model-item label="印章类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="yzlx">
                  <j-multi-select-tag
                    :disabled="formDisabled"
                    type="select"
                    v-model="model.yzlx"
                    dictCode="yzlx_type"
                    placeholder="请选择印章类型"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="isShowSeal">
                <a-form-model-item label="用印份数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="yyfs">
                  <a-input-number
                    :disabled="formDisabled"
                    :max="99999999"
                    :min="0"
                    v-model="model.yyfs"
                    placeholder="请输入用印份数"
                    style="width: 100%"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <!--迭代16.8 增加是否存档字段 -->
                <a-form-model-item label="是否存档" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sfcd">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="radio"
                    v-model="model.sfcd"
                    dictCode="yes_no"
                    placeholder="请选择是否存档"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="model.sfcd==='1'">
                <!--迭代16.8 增加是否存档字段 -->
                <a-form-model-item label="合同存档份数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="cdfs">
                  <a-input-number :disabled=formDisabled :max="99999999" :min="0" v-model="model.cdfs"
                                  placeholder="请输入合同存档份数" style="width: 100%"/>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="48" v-if="!isShowSeal">
              <a-col :span="12">
                <a-form-model-item label="合同原件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="masterCopy">
                  <j-upload v-if="!formDisabled" :remove="false" :disabled="formDisabled" v-model="model.masterCopy"></j-upload>
                  <a-button  icon="download" @click="viewFile(model.masterCopy)">文件列表</a-button>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="48">
              <a-col :span="8" :hidden="model.htlx == '1'">
                <a-form-model-item label="关联收款合同" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="glskht">
                  <j-dict-select-tag
                    :disabled="formDisabled ? true : isFkht ? false : true"
                    type="radio"
                    v-model="model.glskht"
                    dictCode="yn"
                    placeholder="请选择关联收款合同"
                    @change="glskhtChange"
                    :triggerChange="true"/>
                </a-form-model-item>
              </a-col>
              <template v-if="glhtFlag">
                <a-col :span="8">
                  <a-form-model-item label="收款合同名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="skhtmc">
                    <select-contract-manager-input
                      :muitFlag = "true"
                      :disabled="formDisabled"
                      v-model="model.skhtmc"
                      htlx="1"
                      @back="skhtBack"
                      :allList="true"
                      :triggerChange="true"/>
                  </a-form-model-item>
                </a-col>
<!--                <a-col :span="8">-->
<!--                  <a-form-model-item label="甲方" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="jf">-->
<!--                    <select-Company-input :disabled="formDisabled" v-model="model.jf" placeholder="请选择甲方"/>-->
<!--                  </a-form-model-item>-->
<!--                </a-col>-->
<!--                <a-col :span="8">-->
<!--                  <a-form-model-item label="乙方" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="yf">-->
<!--                    <select-customer-input  :disabled="formDisabled" v-model="model.yf" commercialType="2"/>-->
<!--                  </a-form-model-item>-->
<!--                </a-col>-->
                <a-col :span="8">
                  <a-form-model-item label="收款合同额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="skhte">
                    <a-input-number
                      disabled
                      :max="99999999"
                      :min="0"
                      v-model="model.skhte"
                      placeholder="请输入收款合同额"
                      style="width: 100%"
                      @blur="convertMoney1"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="收款合同额大写" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="skhtedx">
                    <a-input disabled v-model="model.skhtedx" placeholder="请输入收款合同额大写"></a-input>
                  </a-form-model-item>
                </a-col>
              </template>
            </a-row>
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="本次合同额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bchte">
                  <a-input-number
                    :precision="2"
                    :disabled="formDisabled"
                    :max="99999999"
                    :min="0"
                    v-model="model.bchte"
                    placeholder="请输入本次合同额"
                    style="width: 100%"
                    @change="convertMoney2"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="本次合同额大写" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bchtedx">
                  <a-input :disabled="formDisabled" v-model="model.bchtedx" placeholder="请输入本次合同额大写"></a-input>
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8">
                <a-form-model-item label="服务期限开始时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fwqx">
                  <j-date :disabled="formDisabled" placeholder="请选择服务期限开始时间" v-model="model.fwqx" style="width: 100%"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="服务期限结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fwqxEnd">
                  <j-date :disabled="formDisabled" placeholder="请选择服务期限结束时间" v-model="model.fwqxEnd" style="width: 100%"/>
                </a-form-model-item>
              </a-col> -->
              <a-col :xl="6" :lg="7" :md="8" :sm="24">
                <a-form-item label="服务期限">
                  <a-range-picker
                  :disabled="formDisabled"
                  :allowClear="false"
                  v-model="createTime"
                  style="width: 100%"
                  @change="createTimeChange"/>
                  </a-form-item>
              </a-col>
              <template>
                <a-divider style="top:20px;">{{ this.firstTitle }}</a-divider>
                <a-col :span="24">
                  <a-table
                    ref="table"
                    size="middle"
                    rowKey="id"
                    :loading="loading"
                    :columns="columns4"
                    :pagination="false"
                    :data-source="dataSource4">
                    <span slot="action" slot-scope="text, record">
                    </span>
                  </a-table>
                </a-col>

                <a-divider style="top:20px;">{{ this.secondTitle }}</a-divider>
                <a-col :span="24">
                  <a-table
                    ref="table"
                    size="middle"
                    rowKey="id"
                    :loading="loading"
                    :columns="columns3"
                    :pagination="false"
                    :data-source="dataSource3">
                    <span slot="action" slot-scope="text, record">
                    </span>
                  </a-table>
                </a-col>
              </template>
              <template  v-if="this.model.htlx == '1'">
              <a-divider style="top:20px;">任务信息</a-divider>
              <template v-if="!detailFlag">
                <a-col :span="24">
                  <j-vxe-table
                    ref="vTable"
                    row-number
                    keep-source
                    height="auto"
                    :loading="loading"
                    :dataSource="dataSource2"
                    :columns="columns2"
                    style="margin-top: 8px;"
                    @valueChange="handleValueChange"
                  >
                  </j-vxe-table>
                </a-col>
              </template>
              <template v-else>
                <a-col :span="24">
                  <a-table
                    ref="table"
                    size="middle"
                    rowKey="id"
                    :loading="loading"
                    :columns="detailColumns"
                    :pagination="false"
                    :data-source="dataSource2">
                  </a-table>
                </a-col>
              </template>
            </template>
              <a-divider style="top:20px;">收付款计划</a-divider>
              <template v-if="sfbg">
                <a-col :span="8">
                  <a-form-model-item label="是否变更款项信息" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sfbgkxxx">
                    <j-dict-select-tag
                      :disabled="formDisabled"
                      type="radio"
                      v-model="model.sfbgkxxx"
                      dictCode="yn"
                      :triggerChange="true"
                      @change="handleChangeSfbgkxxx"
                      placeholder="请选择是否变更款项信息"/>
                  </a-form-model-item>
                </a-col>
              </template>

                <a-col :span="24">
                  <a-table
                    ref="table"
                    size="middle"
                    rowKey="id"
                    :scroll="{x:'100%'}"
                    :loading="loading"
                    :columns="columns"
                    :pagination="false"
                    :data-source="dataSource">
                    <span slot="action" slot-scope="text, record">
                    </span>
                  </a-table>
                </a-col>


              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bz">
                  <a-textarea :maxLength="500" :disabled="formDisabled" v-model="model.bz" rows="4" placeholder="请输入备注"/>
                </a-form-model-item>
              </a-col>

              <a-col :span="24">
                <a-form-model-item label="邮寄信息" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="yjxx">
                  <a-textarea :maxLength="500" :disabled="formDisabled" v-model="model.yjxx" rows="4" placeholder="请输入邮寄信息"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24" v-if="model.htlx == '2'">
                <a-form-model-item label="合同原件扫描件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractOrgFile">
                  <a-button icon="download" @click="viewFile(model.contractOrgFile)">文件列表</a-button>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="相关附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="xgfj">
                  <j-upload :remove="false" v-if="!formDisabled" :disabled="formDisabled" v-model="model.xgfj"></j-upload>
                  <a-button v-else icon="download" @click="viewFile(model.xgfj)">文件列表</a-button>
                </a-form-model-item>
              </a-col>

              <!-- <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
                <a-button @click="submitForm">提 交</a-button>
              </a-col> -->
            </a-row>
          </a-form-model>
          <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
          <view-file-modal ref="viewFileModal"></view-file-modal>
          <!--收付款计划-->
          <erp-omc-contract-manager-plan-modal :htlx="model.htlx+''" :bchte="remainBchte" ref="itemList" ></erp-omc-contract-manager-plan-modal>
          <erp-omc-contract-manager-class-modal ref="itemList2"></erp-omc-contract-manager-class-modal>
          <erp-omc-contract-manager-trustee-modal
            :htlx="model.htlx"
            ref="itemList3"
           ></erp-omc-contract-manager-trustee-modal>
          <erp-omc-contract-manager-entrust-modal
            :htlx="model.htlx"
            ref="itemList4"
            ></erp-omc-contract-manager-entrust-modal>
        </j-form-container>
      </a-spin>
    </a-card>
    <template slot="footer">
      <a-button @click.stop="()=>{visible=false}">关闭</a-button>
    </template>
    <!-- 项目详情开始 -->
    <erp-project-report-modal  ref="projectModalForm"></erp-project-report-modal>
  </a-modal>
</template>

<script>
import { getAction, httpAction } from '@/api/manage'
import { viewFile } from '@/utils/util'
import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import SelectCustomerInput from '@/views/scy/components/SelectCustomerInput'
import SelectContractInput from '@/views/scy/components/SelectContractInput'
import { convertCurrency } from '@/utils/MoneyConvert'
import ViewFileModal from '@/views/scy/components/ViewFileModal'
import ErpOmcContractManagerPlanModal from '@views/erp/omc/contractmanager/modules/ErpOmcContractManagerPlanModal.vue'
import ErpOmcContractManagerClassModal from '@views/erp/omc/contractmanager/modules/ErpOmcContractManagerClassModal'
import ErpOmcContractManagerTrusteeModal from '@views/erp/omc/contractmanager/modules/ErpOmcContractManagerTrusteeModal'
import ErpOmcContractManagerEntrustModal from '@views/erp/omc/contractmanager/modules/ErpOmcContractManagerEntrustModal'
import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
import SelectContractManagerInput from '@/views/scy/components/SelectContractManagerInput'
import moment from 'moment';
import { mapGetters } from 'vuex';
import { message } from 'ant-design-vue'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
import SelectPurchaseCalibrationInput from '@/views/scy/components/SelectPurchaseCalibrationInput'
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import ErpProjectReportModal from '@/views/erp/report/project/modules/ErpProjectReportModal'
import SelectPurchaseApplyFormContractInput from '@/views/scy/components/SelectPurchaseApplyFormContractInput'
export default {
  name: 'ErpOmcContractManagerForm',
  mixins: [viewFile],
  components: { // select-customer-input
    SelectPurchaseApplyFormContractInput,
    ErpProjectReportModal,
    SelectPurchaseCalibrationInput,
    SelectProjectInput,
    SelectTeamInput,
    SelectUserByDep,
    SelectCustomerInput,
    SelectContractInput,
    ViewFileModal,
    ErpOmcContractManagerPlanModal,
    ErpOmcContractManagerClassModal,
    ErpOmcContractManagerTrusteeModal,
    ErpOmcContractManagerEntrustModal,
    SelectContractManagerInput,
    SelectCompanyInput,
    CommonFlowList
  },
  props: {
    // 流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    // 表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      model: {
        // 迭代11 1.是否用章改为是否用印，变更为必选项，不给默认值
        // sfyz: 0,
        glskht: 0,
        sfbgkxxx: 0,
        jf: undefined,
        yf: undefined,
        involveMultiple: 0
      },
      createTime: [],
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      confirmLoading: false,
      visible: false,
      validatorRules: {
        htlx: [
          { required: true, message: '请输入合同类型!' }
        ],
        htmc: [
          { required: true, message: '请输入合同名称!' }
        ],
        xmmc: [
          { required: true, message: '请输入项目名称!' }
        ],
        jytd: [
          { required: true, message: '请输入经营团队!' }
        ],
        yjgsnd: [
          { required: true, message: '请输入业绩归属年度!' }
        ],
        qddw: [
          { required: true, message: '请输入签订单位!' }
        ],
        xmcjr: [
          { required: true, message: '请输入项目承接人!' }
        ],
        yzdw: [
          { required: true, message: '请输入业主单位!' }
        ],
        // qdrq: [
        //   { required: true, message: '请输入签订日期!' }
        // ],
        yzlx: [
          { required: true, message: '请选择印章类型!' }
        ],
        yyfs: [
          { required: true, message: '请填写用印份数!', trigger: 'blur' },
          { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' }
        ],
        lxfs: [
          { required: false },
          { pattern: /(^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$)|(^\/$)/, message: '请输入正确的联系方式!' }
        ],
        masterCopy: [
          { required: true, message: '请上传合同原件!'  }
        ],
        sfyz: [
          { required: true, message: '请选择是否用印!'  }
        ]
      },
      url: {
        add: '/api/erp/omc/contractmanager/erpOmcContractManager/add',
        edit: '/api/erp/omc/contractmanager/erpOmcContractManager/edit',
        queryProjectDeposit: '/api/erp/finance/deposit/erpFinanceProjectDepositBill/queryByEntity',
        queryById: '/api/erp/omc/contractmanager/erpOmcContractManager/queryById',
        queryPlanList: '/api/erp/omc/contractmanager/erpOmcContractManagerPlan/listAll',
        queryClassList: '/api/erp/omc/contractmanager/erpOmcContractManagerClass/listAll',
        queryClassList2: '/api/erp/omc/project/erpOmcProjectTask/list',
        queryEntrustList: '/api/erp/omc/contractmanager/erpOmcContractManagerEntrust/listAll',
        queryTrusteeList: '/api/erp/omc/contractmanager/erpOmcContractManagerTrustee/listAll',
        generatedFormNumber: '/api/erp/base/generatedFormNumber',
        queryProjectById: '/api/erp/project/report/erpProjectReport/queryById'
      },
      loading: false,
      columns: [
        {
          title: '款项名称',
          align: 'center',
          dataIndex: 'kxmc',
           ellipsis: true,
        },
        {
          title: '金额(元)',
          align: 'center',
          dataIndex: 'je',
           ellipsis: true,
        },
        {
          // 3.收付款计划列表中的款项时间改为预计款项时间，为必填
          title: '预计款项日期',
          align: 'center',
          dataIndex: 'kxrq',
           ellipsis: true,
        },
        {
          title: '款项节点说明',
          align: 'center',
          dataIndex: 'kxjdsm',
           ellipsis: true,
        },
      ],
      columns2: [
        {
          title: '业务编码',
          align: 'center',
          key: 'ywfl',
          formatter: ({ cellValue}) => {
            return cellValue ? filterMultiDictText(this.dictOptions['ywfl'], cellValue + '') : ''
          }
        },
        {
          title: '业务名称',
          align: 'center',
          key: 'ywmc'
        },
        {
          title: '合同占比(%)',
          align: 'center',
          key: 'htzb',
          type: JVXETypes.inputNumber,
        },
        {
          title: '分配合同额（元）',
          align: 'center',
          key: 'fphte',
          type: JVXETypes.inputNumber,
        },
        {
          title: '生产团队',
          align: 'center',
          key: 'sctd_dictText',
          // formatter: ({ cellValue }) => {
          //   return cellValue ? filterMultiDictText(this.dictOptions['sctd'], cellValue + '') : ''
          // }
        },
        {
          title: '团队负责人',
          align: 'center',
          key: 'tdfzr_dictText',
          // formatter: ({ cellValue }) => {
          //   return cellValue ? filterMultiDictText(this.dictOptions['tdfzr'], cellValue + '') : ''
          // }
        }
      ],
      columns3: [
        {
          title: '名称',
          align: 'center',
          dataIndex: 'gsdaId',
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['gsda'], text + '')
            }
          }
        },
      ],
      detailColumns: [
        {
          title: '业务编码',
          align: 'center',
          dataIndex: 'ywfl',
        },
        {
          title: '业务名称',
          align: 'center',
          dataIndex: 'ywmc'
        },
        {
          title: '合同占比(%)',
          align: 'center',
          dataIndex: 'htzb',
        },
        {
          title: '分配合同额（元）',
          align: 'center',
          dataIndex: 'fphte',
        },
        {
          title: '生产团队',
          align: 'center',
          dataIndex: 'sctd_dictText',
        },
        {
          title: '团队负责人',
          align: 'center',
          dataIndex: 'tdfzr_dictText',
        }
      ],
      columns4: [
        {
          title: '名称',
          align: 'center',
          dataIndex: 'khdaId',
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['khda'], text + '')
            }
          }
        },
      ],
      contractType: '',
      dataSource: [], // 收付款计划数据源
      dataSource2: [], // 任务信息
      dataSource3: [], // 公司信息
      dataSource4: [], // 客户信息
      dictOptions: {},
      projectName: '',
      // 迭代11 委托方改为委托方(合同甲方)，受托方改为受托方（合同乙方）
      firstTitle: '委托方(合同甲方)信息',
      secondTitle: '受托方(合同乙方)信息',
      cust_lxr: 'erp_omc_customer_manager_contact,lxr,id',
      glhtFlag: false,
      sfbg: false,
      detailFlag: false,  //查看详情状态
      isFkht: false,
      showKxxx: false,
      // 修改时加上当前行的值
      editRemain: 0,
      involveMultipleFlag: false
    }
  },
  watch:{
    dataSource:{
      immediate: true,
      handler(val,old){
        console.log("remain:"+this.remainBchte)
        // this.remain = this.remainBchte;
      }
    }
  },
  computed: {
    showByHtlx () {
      var type = this.contractType;
      if (type == '1' || type == '2') {
        return true
      } else {
        return false
      }
    },
    formDisabled() {
        return true
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    },
    isShowSeal () {
      if (this.model.sfyz && this.model.sfyz == 1) {
        return true
      } else {
        return false
      }
    },
    // 合同额剩余可分配值
    remainBchte(){
      if(this.model.bchte){
        let remain = this.model.bchte + this.editRemain;
        this.dataSource.forEach(data=>{
          remain -= data.je;
        })
        return remain;
      }else{
        return 0;
      }
    }
  },
  created() {
    // 备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
    this.resetScreenSize();
    // 如果是流程中表单，则需要加载流程表单data
    this.initDictConfig();
  },
  methods: {
    getProjectDetail(id) {
      const that = this
      this.$nextTick(() => {
        getAction(this.url.queryProjectById, { id }).then((res) => {
          if (res.success) {
            const model = res.result
            that.$refs.projectModalForm.getDetail(model);
            that.$refs.projectModalForm.title = '项目一览表';
          }
        })
      })
    },
    // 触发屏幕自适应
    resetScreenSize() {
      let screenWidth = document.body.clientWidth;
      if (screenWidth < 500) {
        this.scrollTrigger = { x: 800 };
      } else {
        this.scrollTrigger = {};
      }
    },
    handleCancel() {
      this.visible = false;
    },
    initDictConfig() {
      initDictOptions('ywfx_type').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'ywfl', res.result)
        }
      })
      initDictOptions('YES_OR_NO').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'yes_or_no', res.result)
        }
      })
      //
      // initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
      //   if (res.success) {
      //     this.$set(this.dictOptions, 'sctd', res.result)
      //   }
      // })
      //
      // initDictOptions('erp_employee_file,name,id').then((res) => {
      //   if (res.success) {
      //     this.$set(this.dictOptions, 'tdfzr', res.result)
      //   }
      // })

      initDictOptions('erp_purchase_supplier,enterprise_name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'khda', res.result)
        }
      })

      initDictOptions('erp_company_files,file_name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'gsda', res.result)
        }
      })
    },
    yzdwChange() {
      this.$set(this.model, 'lxr', undefined);
      this.$set(this.model, 'lxfs', undefined);
      // this.cust_lxr = erp_omc_customer_manager_contact,lxr,id;
      this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.yzdw + '\'';
      // this.$set(this.model, 'lxr', undefined);
      // this.$set(this.model, 'lxfs', undefined);
    },
    lxrChange(val) {
      //debugger
      getAction('/api/erp/omc/customermanager/erpOmcCustomerManagerContact/queryById', { id: val }).then((res) => {
        if (res.success) {
          let data = res.result.records || res.result
          // debugger;
          // this.model.lxdh = data.lxfs;
          this.$set(this.model, 'lxr', val)
          this.$set(this.model, 'lxfs', data.lxfs)
        }
      })
    },
    ...mapGetters(['userInfo']),
    add(type) {
      this.contractType = type
      this.dataSource = []
      this.dataSource2 = []
      this.dataSource3 = []
      this.dataSource4 = []
      this.modelDefault.lx = 1
      this.modelDefault.htlx = type
      console.log(this.contractType);
      this.sfbg = false;
      this.edit(this.modelDefault);
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
      this.model.proposer = this.userInfo().empId;
      this.model.proposerDeptId = this.userInfo().deptId;
      this.showKxxx = true;
      this.involveMultipleFlag = false;
      this.generatedFormNumber();
    },
    generatedFormNumber() {
      getAction(this.url.generatedFormNumber, { prefix: 'HT', subSystemCode: '05' }).then(res => {
        if (res.success) {
          this.$set(this.model, 'htbh', res.result)
        }
      })
    },
    add2(type) {
      console.log("add2  form:"+type);
      this.contractType = type
      this.dataSource = []
      this.dataSource2 = []
      this.dataSource3 = []
      this.dataSource4 = []
      this.modelDefault.lx = 2
      this.sfbg = true
      this.modelDefault.htlx = type
      console.log("add2  formcontractType:"+ this.contractType );
      this.edit(this.modelDefault);
      this.model.proposer = this.userInfo().empId;
      this.model.proposerDeptId = this.userInfo().deptId;
      this.showKxxx = false;
      this.involveMultipleFlag = false;
      this.$set(this.validatorRules,'sfyz',[{ required: true, message: '请选择是否用印!' }])
      this.generatedFormNumber();
    },
    edit(record) {
      this.$refs.form.resetFields();
      this.model = Object.assign({}, record);
      if (record.lx == 2) {
        this.sfbg = true
        this.$set(this.validatorRules,'caId',[{ required: true, message: '请选择合同编号!' }])
        this.$set(this.validatorRules,'bglx',[{ required: true, message: '请选择变更类型!' }])
        this.$set(this.validatorRules,'sfyz',[{ required: true, message: '请选择是否用印!' }])
      } else {
        this.sfbg = false;
        this.$delete(this.validatorRules,'caId')
        this.$delete(this.validatorRules,'bglx')
      }
      if (this.model && this.model.htlx) {
        this.projectName = this.model.xmmc_dictText
        if (this.model.htlx === '1' || this.model.htlx === 1) {// 收款合同
          // 客户
          this.$refs.itemList4.isFk = true
          // 公司
          this.$refs.itemList3.isFk = false
          this.changeTitle(this.model.htlx)
        } else {// 付款合同
          // 客户
          this.$refs.itemList4.isFk = false
          // 公司
          this.$refs.itemList3.isFk = true
          this.changeTitle(this.model.htlx)
        }
      } else {// 默认
        // 客户
        this.$refs.itemList4.isFk = false
        // 公司
        this.$refs.itemList3.isFk = true
        this.changeTitle()
      }
      // 详情页去除表头中的操作
      if(this.formDisabled){
        this.columns3.pop()
        this.columns4.pop()
      }
      this.$set(this, 'isFkht', this.model.htlx != '1')
      this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.yzdw + '\'';
      if (this.model.id) {
        // 收款计划
        getAction(this.url.queryPlanList, { mainId: this.model.id }).then((res) => {
          if (res.success) {
            this.dataSource = res.result || res.result.records
          }
        })

        if(this.model.htlx == '1'){
          getAction(this.url.queryClassList, { mainId: this.model.id }).then((res) => {
            if (res.success) {
              this.dataSource2 = res.result.records || res.result
            }
          })
        }else{
          this.dataSource2=[];
        }
        
        // 任务信息

        // 公司信息
        getAction(this.url.queryTrusteeList, { mainId: this.model.id }).then((res) => {
          if (res.success) {
            this.dataSource3 = res.result.records || res.result
          }
        })

        // 客户信息
        getAction(this.url.queryEntrustList, { mainId: this.model.id }).then((res) => {
          if (res.success) {
            this.dataSource4 = res.result.records || res.result
          }
        })
        this.showKxxx = this.model.lx == 2 ? this.model.sfbgkxxx == '1' : true
        this.glhtFlag = this.model.glskht == '1' ? true : false
      }
  //    this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
      // this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id';
      // this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.yzdw + '\'';
      this.involveMultipleFlag = record.involveMultiple == 1
      // 服务期限
      if(!!this.model.fwqx&&!!this.model.fwqxEnd){
        this.createTime = []
        this.createTime.push(this.model.fwqx)
        this.createTime.push(this.model.fwqxEnd)
      }else{
        this.createTime = []
      }
      this.visible = true;
    },
    // 初始化加载数据
    initData(val) {
      let params = { id: val };
      getAction(this.url.queryById, params).then((res) => {
        if (res.success) {
          this.detailFlag = true;
          this.edit(res.result);
        }
      });
    },
    submitForm() {
      const that = this;
      // 判断收款计划金额是否大于合同金额
      let planSum = 0;
      this.dataSource.forEach(data=>{
        planSum += data.je;
      });
      console.log("计划总金额:"+planSum)
      // 迭代11 TASK#3763 2.收付款计划栏金额与合同总金额不对等时不可以发起，需要校验核对收付款计划金额和合同总金额
      if(this.model.bchte!=planSum){
        message.warning("计划总金额与合同金额不对等!")
        this.$emit('unButtonDisable');
        return;
      }
      let total = 0
      this.dataSource2.forEach(val => {
        total += val.fphte
      })
      console.log(this.dataSource2,total,'===================分项的金额和总额需要做相等的校验');
      if(total !== this.model.bchte){
        message.warning('分配项金额和本次合同额不相等，请重新填写')
        this.$emit('unButtonDisable');
        return;
      }
      console.log('委托方和受托方列表的校验start');
      // 迭代11 委托方和受托方列表需要校验两个分别必须至少有一条数据 是否为收付款单位有各且仅有一个
      if(!this.validateClientDetailAndTrusteeDetail()){
        this.$emit('unButtonDisable');
        return;
      }
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if (!this.model.id) {
            httpurl += this.url.add;
            method = 'post';
          } else {
            httpurl += this.url.edit;
            method = 'put';
          }
          //迭代11 标题修改
          that.model.bpmBizTitle = that.projectName + '-' + that.userInfo().empName + '-' + that.model.htbh
          if (that.model.htlx === 1 || that.model.htlx === '1') {
            if (that.dataSource.length === 0) {
              that.$message.warn('请填写收付款计划');
              that.confirmLoading = false
              that.$emit('unButtonDisable');
              return;
            }
          }
          let model = {};
          Object.assign(model, this.model)
          // if (model.bchte) {
            // this.$set(this.model,"yjhte",yjhte * 100)
          //   model.bchte = model.bchte * 100;
          // }

          // 收付款计划
          model.planList = this.dataSource;

          // for (let i = 0; i < model.planList.length; i++) {
          //   // debugger;
          //   model.planList[i].je = model.planList[i].je * 100
          // }

          model.classList = this.dataSource2;
          // 公司
          model.trusteeList = this.dataSource3;
          // 客户
          model.entrustList = this.dataSource4;

          // debugger;

          httpAction(httpurl, model, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.$emit('ok');
            } else {
              that.$message.warning(res.message);
              that.$emit('unButtonDisable');
            }
          }).catch((error) => {
            that.$emit('unButtonDisable');
          }).finally(() => {
            that.confirmLoading = false;
          })
        } else {
          that.$emit('unButtonDisable');
        }
      })
    },
    convertMoney1() {
      let money = this.model.skhte
      this.$set(this.model, 'skhtedx', convertCurrency(money))
    },
    convertMoney2() {
      let money = this.model.bchte
      this.$set(this.model, 'bchtedx', convertCurrency(money))
      this.dataSource2.forEach((item, index) => {
        item.finalId = item.id
        if (this.model.bchte && item.htzb) {
          // item.fphte = this.model.bchte * item.htzb / 100
          let amount = item.fphte / this.model.bchte * 100
          item.htzb = Math.round((amount + Number.EPSILON) * 100) / 100;
        }
      })
    },
    handleValueChange(event){
      const { rowIndex, columnIndex,value } = event
      if(this.model.bchte){
        if(columnIndex == 3){
          let amount = this.model.bchte * value / 100
          this.dataSource2[rowIndex].fphte = Math.round((amount + Number.EPSILON) * 100) / 100;
        } else if (columnIndex == 4){
          let rate = value / this.model.bchte * 100
          this.dataSource2[rowIndex].htzb = Math.round((rate + Number.EPSILON) * 100) / 100;
        }
      }
    },
    xmmcChange(val) {
      getAction('/api/erp/omc/project/erpOmcProject/queryById', { id: val }).then((res) => {
        if (res.success) {
          let data = res.result.records || res.result
          this.$set(this.model, 'yzdw', data.ownerUnit) // 业主单位
          this.$set(this.model, 'bail', '0')
          // debugger;
          // this.model.lxdh = data.lxfs;
          this.$set(this.model, 'xmbh', data.finalNo) // 项目编号
          this.$set(this.model, 'jytd', data.teamName) // 经营团队
          this.$set(this.model, 'yjgsnd', data.year) // 业绩归属年度
          this.$set(this.model, 'qddw', data.signUnit) // 签定单位
          this.$set(this.model, 'xmcjr', data.undertaker) // 项目承接人
          this.$set(this.model, 'lxfs', data.contactTel) // 联系方式
          this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.yzdw + '\'';
          this.$set(this.model, 'lxr', data.contacts) // 联系人
          this.projectName = data.projectName
          // 任务信息
          getAction(this.url.queryClassList2, { pageNo:1,pageSize: 999,projectId: data.id }).then((res) => {
            this.dataSource2 = []
            if (res.success) {
              let data = res.result.records || res.result
              // debugger;
              for (let i = 0; i < data.length; i++) {
                let d = {
                  'ywfl': data[i].categoryCode,
                  'ywmc': data[i].categoryName,
                  'htzb': data[i].contractRate,
                  'fphte': data[i].contractAmount,
                  'sctd': data[i].productTeam,
                  'sctd_dictText': data[i].productTeam_dictText,
                  'tdfzr': data[i].teamLeader,
                  'tdfzr_dictText': data[i].teamLeader_dictText,
                  'projectTaskId': data[i].id
                };
                let index = this.dataSource2.findIndex(item => item.ywfl == d.ywfl)
                if(index > -1){
                  this.dataSource2.splice(index, 1, d)
                }else{
                  this.dataSource2.push(d);
                }
              }
            }
          })
          var params = {
            preProjectId: data.id,
            feeCategory: '2',
            bpmStatus: '3'
          }
          //查看项目保证金
          getAction(this.url.queryProjectDeposit,  params ).then((res) => {
            if (res.success) {
              let data = res.result.records || res.result
              this.$set(this.model, 'bail', data.remittanceAmount)
            }
          })
        }
      })
    },
    htlxChange(val) {
      this.$set(this.model, 'htlx', val)
      if (val) {
        let url;
        if (val === '1') {
          // 合同类型为收款合同，需要做特殊处理
          // updated  by wuzx at 2021/12/28 调整为立项底表查询,不带bpmStatus
          // 修改前:  url = '/api/erp/omc/project/erpOmcProjectApply/list2?bpmStatus=3&isSkht=true";
          // 修改后:
          url = '/api/erp/omc/project/erpOmcProject/list2?isSkht=true';
          this.$set(this.model, 'glskht', '0')
          this.glhtFlag = false;
          // 将受托方子modal中的是否显示付款改为false
          this.$refs.itemList4.isFk = true
          this.$refs.itemList3.isFk = false
          this.changeTitle(val)
        } else {
          // 合同类型为付款合同，需要做特殊处理
          // updated by wuzx at 2021/12/28 调整为立项底表查询,不带bpmStatus
          // 修改前: url = '/api/erp/omc/project/erpOmcProjectApply/list2?bpmStatus=3&isSkht=false";
          // 修改后:
          url = '/api/erp/omc/project/erpOmcProject/list2?isSkht=false';
          // 将受托方子modal中的是否显示付款改为true
          this.$refs.itemList4.isFk = false
          this.$refs.itemList3.isFk = true
          this.changeTitle(val)
        }
        this.$set(this, 'isFkht', val !== '1');
        this.$refs.projectModel.loadData(url);
      }
      // 切换合同类型时清空委托方、受托方信息
      this.dataSource4 = [];
      this.dataSource3 = [];
    },
    glskhtChange(val) {
      console.log(val);
      // debugger;
      this.$set(this.model, 'glskht', val)
      if (val) {
        if (val === '1') {
          this.glhtFlag = true;
        } else {
          this.glhtFlag = false;
        }
      }
    },
    changeTitle(args) {
      console.log("合同类型=====",args)
       if (args == '1') {// 收款合同类型时
         this.firstTitle = '委托方(合同甲方)信息'
         this.secondTitle = '受托方(合同乙方)信息'
          // 修改列表表头
          this.$set(this,'columns4',[
            {
              title: '名称',
              align: 'center',
              dataIndex: 'khdaId',
              customRender: (text) => {
                if (!text) {
                  return ''
                } else {
                  return filterMultiDictText(this.dictOptions['khda'], text + '')
                }
              }
            },
            {
              title: '是否为付款单位',
              align: 'center',
              dataIndex: 'isFk',
              customRender: (text) => {
                if (!text) {
                  return ''
                } else {
                  return filterMultiDictText(this.dictOptions['yes_or_no'], text + '')
                }
              }
            },
            {
              title: '操作',
              dataIndex: 'action',
              align: 'center',
              scopedSlots: {
                filterDropdown: 'filterDropdown',
                filterIcon: 'filterIcon',
                customRender: 'action'
              }
            }
            ])
            this.$set(this,'columns3',[
            {
              title: '名称',
              align: 'center',
              dataIndex: 'gsdaId',
              customRender: (text) => {
                if (!text) {
                  return ''
                } else {
                  return filterMultiDictText(this.dictOptions['gsda'], text + '')
                }
              }
            },
            {
              title: '是否为收款单位',
              align: 'center',
              dataIndex: 'isSk',
              customRender: (text) => {
                if (!text) {
                  return ''
                } else {
                  return filterMultiDictText(this.dictOptions['yes_or_no'], text + '')
                }
              }
            },
              {
                title: '操作',
                dataIndex: 'action',
                align: 'center',
                scopedSlots: {
                  filterDropdown: 'filterDropdown',
                  filterIcon: 'filterIcon',
                  customRender: 'action'
                }
              }
          ])
       } else {// 付款合同类型时
         this.firstTitle = '受托方(合同乙方)信息'
         this.secondTitle = '委托方(合同甲方)信息'
         // 修改列表表头
          this.$set(this,'columns4',[
            {
              title: '名称',
              align: 'center',
              dataIndex: 'khdaId',
              customRender: (text) => {
                if (!text) {
                  return ''
                } else {
                  return filterMultiDictText(this.dictOptions['khda'], text + '')
                }
              }
            },
            {
              title: '是否为收款单位',
              align: 'center',
              dataIndex: 'isSk',
              customRender: (text) => {
                if (!text) {
                  return ''
                } else {
                  return filterMultiDictText(this.dictOptions['yes_or_no'], text + '')
                }
              }
            },
            {
              title: '操作',
              dataIndex: 'action',
              align: 'center',
              scopedSlots: {
                filterDropdown: 'filterDropdown',
                filterIcon: 'filterIcon',
                customRender: 'action'
              }
            }
            ])
            this.$set(this,'columns3',[
            {
              title: '名称',
              align: 'center',
              dataIndex: 'gsdaId',
              customRender: (text) => {
                if (!text) {
                  return ''
                } else {
                  return filterMultiDictText(this.dictOptions['gsda'], text + '')
                }
              }
            },
            {
              title: '是否为付款单位',
              align: 'center',
              dataIndex: 'isFk',
              customRender: (text) => {
                if (!text) {
                  return ''
                } else {
                  return filterMultiDictText(this.dictOptions['yes_or_no'], text + '')
                }
              }
            },
            {
              title: '操作',
              dataIndex: 'action',
              align: 'center',
              scopedSlots: {
                filterDropdown: 'filterDropdown',
                filterIcon: 'filterIcon',
                customRender: 'action'
              }
            }
          ])
       }
    },
    htbhChange(val) {
      getAction('/api/erp/omc/contractmanager/erpOmcContractManagerFinal/queryById', { id: val }).then((res) => {
        if (res.success) {
          let data = res.result.records || res.result
                   // debugger;
          this.$set(this.model, 'caId', val)
          this.$set(this.model, 'bpmBizTitle', data.htmc) // 标题
          this.$set(this.model, 'htmc', data.htmc) // 合同名称
          this.$set(this.model, 'htlx', data.htlx) // 合同类型
          // fix:BUG#4955 合同变更-当合同类型为付款合同，带出的委托方、受托方信息错误 start
          this.htlxChange(data.htlx)
          // fix:BUG#4955 合同变更-当合同类型为付款合同，带出的委托方、受托方信息错误 end
          this.$set(this.model, 'xmmc', data.xmmc) // 项目名称
          this.$set(this.model, 'jytd', data.jytd) // 经营团队
          this.$set(this.model, 'yjgsnd', data.yjgsnd)// 业绩归属年度
          this.$set(this.model, 'qddw', data.qddw) // 签订单位
          this.$set(this.model, 'xmcjr', data.xmcjr) // 项目承认人
          this.$set(this.model, 'yzdw', data.yzdw)// 业主单位
          this.$set(this.model, 'lxr', data.lxr)// 联系人
          this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.yzdw + '\'';
          this.$set(this.model, 'lxfs', data.lxfs) // 联系方式
          this.$set(this.model, 'qdrq', data.qdrq)// 签订日期
          this.$set(this.model, 'sfyz', data.sfyz)// 是否用印
          this.$set(this.model, 'yzlx', data.yzlx) // 印章类型
          this.$set(this.model, 'yyfs', data.yyfs)// 用印份数
          this.$set(this.model, 'glskht', data.glskht) // 关联收款合同
          this.glhtFlag = data.glskht == '1'
          this.$set(this.model, 'skhtmc', data.skhtmc) // 收款合同名称
          // this.$set(this.model, 'jf', data.yzdw) // 甲方
          this.$set(this.model, 'jf', data.jf)// 甲方
          this.$set(this.model, 'yf', data.yf)// 甲方
          // this.$set(this.model, 'yf', data.qddw) // 已方
          this.$set(this.model, 'skhte', data.skhte)// 收款合同额
          this.$set(this.model, 'skhtedx', data.bchtedx)// 收款合同额大写

          let bchte = data.bchte;
          // if (data.bchte) {
          //   bchte = data.bchte / 100
          // }

          this.$set(this.model, 'bchte', bchte)
          this.$set(this.model, 'bchtedx', data.bchtedx)
          this.$set(this.model, 'fwqx', data.fwqx)
          this.$set(this.model, 'fwqxEnd', data.fwqxEnd)
          // 服务期限
          if(!!this.model.fwqx&&!!this.model.fwqxEnd){
            this.createTime = []
            this.createTime.push(this.model.fwqx)
            this.createTime.push(this.model.fwqxEnd)
          }else{
            this.createTime = []
          }
          this.$set(this.model, 'bz', data.bz) // 备注
          this.$set(this.model, 'yjxx', data.yjxx) // 邮寄信息
          this.$set(this.model, 'xgfj', data.xgfj) // 相关附件
          this.$set(this.model, 'htbh', data.htbh) // 合同编号
          this.$set(this.model, 'xmbh', data.xmbh) // 合同编号

          this.$set(this.model, 'bglx', data.bglx)
          this.$set(this.model, 'sfbgkxx', data.sfbgkxx)
          //this.$set(this.model, 'proposer', data.proposer)
          //this.$set(this.model, 'proposerDeptId', data.proposerDeptId)
          this.$set(this, 'isFkht', data.htlx != '1')
          this.$set(this.model, 'involveMultiple', data.involveMultiple)
          this.$set(this, 'involveMultipleFlag', data.involveMultiple == 1)
          this.$set(this.model, 'masterCopy', data.masterCopy) // 合同原件
           this.$set(this.model, 'bail', '0')
          //this.yzdwChange();

          // 收款计划
          getAction('/api/erp/omc/contractmanager/erpOmcContractManagerPlanFinal/listAll', { mainId: val }).then((res) => {
            if (res.success) {
              this.dataSource = res.result.records || res.result
              console.log('收款计划', this.dataSource)
              if (this.dataSource.length > 0) {
                this.dataSource.forEach((item, index) => {
                  item.finalId = item.id
                })
              }
            }
          })
           var params = {
            preProjectId: data.xmmc,
            feeCategory: '2',
            bpmStatus: '3'
          }
          //查看项目保证金
          getAction(this.url.queryProjectDeposit,  params ).then((res) => {
            if (res.success) {
              let data = res.result.records || res.result
              this.$set(this.model, 'bail', data.remittanceAmount)
            }
          })
          // 任务信息
          getAction('/api/erp/omc/contractmanager/erpOmcContractManagerClassFinal/listAll', { mainId: val }).then((res) => {
            if (res.success) {
              this.dataSource2 = res.result.records || res.result
              this.dataSource2.forEach((item, index) => {
                item.finalId = item.id
                if (this.model.bchte && item.htzb) {
                  item.fphte = this.model.bchte * item.htzb / 100
                }
              })
            }
          })

          // 受托方信息
          getAction('/api/erp/omc/contractmanager/erpOmcContractManagerTrusteeFinal/listAll', { mainId: val }).then((res) => {
            if (res.success) {
              this.dataSource3 = res.result.records || res.result
              this.dataSource3.forEach((item, index) => {
                item.finalId = item.id
              })
            }
          })

          // 委托方信息
          getAction('/api/erp/omc/contractmanager/erpOmcContractManagerEntrustFinal/listAll', { mainId: val }).then((res) => {
            if (res.success) {
              this.dataSource4 = res.result.records || res.result
              this.dataSource4.forEach((item, index) => {
                item.finalId = item.id
              })
            }
          })
        }
      })
    },
    skhtBack (item) {
      //this.$set(this.model, 'skhtmc', item[0].id)
      this.$set(this.model, 'jf', item[0].qddw)
      this.$set(this.model, 'skhte', item[0].bchte)
      this.$set(this.model, 'skhtedx', item[0].bchtedx)
    },
    handleChangeSfbgkxxx(val) {
      this.$set(this.model, 'sfbgkxxx', val);
      this.$set(this, 'showKxxx', val == '1');
    },
    handleChangeSeal(val) {
      if (val == 0) {
        this.$set(this.validatorRules, 'masterCopy', [{ required: true, message: '请上传合同原件!'  }]);
      } else {
        this.$delete(this.validatorRules, 'masterCopy');
      }
    },
    changeBizTitle() {
      this.model.bpmBizTitle = this.model.htmc
    },
    // 收付款计划子表变化回调
    planDetailListChange(){
      console.log("收付款计划子表变化---》",this.dataSource)
    },
    // 服务期限开始时间 结束时间
    createTimeChange(date, dateString) {
      this.$set(this.model, 'fwqx', dateString[0] + ' 00:00:00')
      this.$set(this.model, 'fwqxEnd', dateString[1] + ' 23:59:59')
    },
    // 校验委托方和受托方子表数据合法性 委托方和受托方列表需要校验两个分别必须至少有一条数据 是否为收付款单位有各且仅有一个
    validateClientDetailAndTrusteeDetail(){
      if(this.model.htlx=='1'){ // 收款合同 dataSource4 客户为委托方（付款）
        console.log("收款合同 dataSource4 :",this.dataSource4)
        // 委托方(合同甲方)信息校验
        if(!!this.dataSource4&&this.dataSource4.length==0){
          message.warning("请填写委托方信息!")
          return false;
        }else{
          let hasFkList = this.dataSource4.filter(item => item.isFk == '1');
          console.log('hasFkList--->', hasFkList)
          if (hasFkList.length <= 0) {
            message.warning('委托方必须有一个付款单位!')
            return false;
          }
        }
        // 受托方(合同乙方)信息校验
        if(!!this.dataSource3&&this.dataSource3.length==0){ // 收款合同 dataSource3 公司为受托方（收款）
          message.warning("请填写受托方信息!")
          return false;
        }else{
          let hasSkList = this.dataSource3.filter(item=>item.isSk=='1');
          console.log("hasSkList--->",hasSkList)
          if(hasSkList.length!=1){
            message.warning("受托方有且仅有一个是收款单位!")
            return false;
          }
        }
        return true;
      }else{// 付款合同 dataSource3 公司为委托方（付款）
        console.log("付款合同 dataSource4 :",this.dataSource4)
        // 委托方(合同甲方)信息校验
        if(!!this.dataSource3&&this.dataSource3.length==0){
          message.warning("请填写委托方信息!");
          return false;
        }else{
          let hasFkList = this.dataSource3.filter(item=>item.isFk=='1');
          console.log("hasFkList--->",hasFkList)
          if(hasFkList.length!=1){
            message.warning("委受托方有且仅有一个是付款单位!")
            return false;
          }
        }
        // 受托方(合同乙方)信息校验
        if(!!this.dataSource4&&this.dataSource4.length==0){
          message.warning("请填写受托方信息!");
          return false;
        }else{
          let hasSkList = this.dataSource4.filter(item=>item.isSk=='1');
          console.log("hasSkList--->",hasSkList)
          if(hasSkList.length!=1){
            message.warning("受托方有且仅有一个是收款单位!")
            return false;
          }
        }
        return true;
      }
    }
  }
}
</script>
<style>
  @import "../../../../../utils/print.css";
</style>